package com.bidevalution.controller.api;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.bidevalution.business.function.FunctionCalculator;
import com.bidevalution.business.service.*;
import com.bidevalution.dao.entity.BeSectionInfo;
import com.bidevalution.service.BidParamService;
import com.bidevalution.support.context.Constants;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.GsonUtil;
import com.qtp.core.util.OConvertUtils;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import com.bidevalution.dao.entity.BeSectionParameter;
import com.google.common.collect.Maps;
import com.qtp.core.model.Response;

@RestController
@RequestMapping("/beSectionParameter")
@Api(tags = "标段参数配置管理")
@Log4j2
public class BeSectionParameterController {

    @Autowired
    private BeSectionParameterService beSectionParameterService;
    @Autowired
    private BeTechnologyItemService beTechnologyItemService;
    @Autowired
    private BeQualificateItemService beQualificateItemService;
    @Autowired
    private BeManagerNodeService beManagerNodeService;
    @Autowired
    private BeBudgetItemService beBudgetItemService;
    @Autowired
    private BidParamService bidParamService;
    @Autowired
    private BeSectionInfoService beSectionInfoService;
    @Value("${IS_CALL_INTERFACE}")
    private String isCallInterface;

    private Logger log = Logger.getLogger(getClass());

    private static final String K1 = "K1";
    private static final String K2 = "K2";
    private static final String DOWN_RATE = "DownRate";

    @ApiOperation(value = "查询所有参数列表", notes = "查询所有参数列表", response = BeSectionParameter.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段ID", required = true, dataType = "String", paramType = "query")})
    @GetMapping("/getParameterList")
    public Response<List<BeSectionParameter>> selectList(@RequestParam("sectionId") String sectionId) {
        return Response.ok(beSectionParameterService.selectList(sectionId));
    }

    @ApiOperation(value = "查询所有参数", notes = "查询所有参数", response = BeSectionParameter.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段ID", required = true, dataType = "String", paramType = "query")})
    @GetMapping("/getParameters")
    public Response<Map<String, Object>> selectParameters(@RequestParam("sectionId") String sectionId) {
        Map<String, Object> dataMap = Maps.newHashMap();
        Map<String,Object> paramMap;
        Map<String,Object> selectMap;
        for (BeSectionParameter beSectionParameter : beSectionParameterService.selectList(sectionId)) {
        	dataMap.put(beSectionParameter.getParamId(), beSectionParameter.getParamValue());
        }
        for (BeSectionParameter beSectionParameter : beSectionParameterService.selectList(sectionId)) {
            if (!StringUtils.isEmpty(beSectionParameter.getDisplayType())) {
            	paramMap = GsonUtil.jsonToMapWithGson(beSectionParameter.getDisplayType());
            	if(paramMap != null) {
            		if("SELECT".equals(paramMap.get("type"))) {
            			selectMap = Maps.newHashMap();
            			for(String item:StringUtils.delimitedListToStringArray(paramMap.get("value").toString(), "|")) {
            				if(item.split(":").length == 2) {
                				selectMap.put(item.split(":")[0], item.split(":")[1]);
            				}
            			}
            			dataMap.put(beSectionParameter.getParamId() + "_DISPLAY_TYPE",selectMap);
            			dataMap.put(beSectionParameter.getParamId(), beSectionParameter.getParamValue());
            		}else if("BITCHECK".equals(paramMap.get("type"))) {
            			//该配置废弃采用公式配置
            			if("1".equals(beSectionParameter.getParamValue())) {
            				dataMap.put(beSectionParameter.getParamId() ,beSectionParameter.getParamValue());
            			}else if("2".equals(beSectionParameter.getParamValue())) {
            				dataMap.put(beSectionParameter.getParamId() ,beSectionParameter.getParamValue());
            			}else if("4".equals(beSectionParameter.getParamValue())) {
            				dataMap.put(beSectionParameter.getParamId() ,beSectionParameter.getParamValue());
            			}else if("3".equals(beSectionParameter.getParamValue())) {
            				//1 2
            				dataMap.put(beSectionParameter.getParamId() ,"1,2");
            			}else if("5".equals(beSectionParameter.getParamValue())) {
            				//1 4
            				dataMap.put(beSectionParameter.getParamId() ,"1,4");
            			}else if("6".equals(beSectionParameter.getParamValue())) {
            				//2 4
            				dataMap.put(beSectionParameter.getParamId() ,"2,4");
            			}else if("7".equals(beSectionParameter.getParamValue())) {
            				//1 2 4
            				dataMap.put(beSectionParameter.getParamId() ,"1,2,4");
            			}
            		}else if("FORMULAR".equals(paramMap.get("type"))) {
            			//该配置方法废弃,采用AEL或者MEL配置
            			if(!StringUtils.isEmpty(paramMap.get("value"))){
            				FunctionCalculator.computeAviator(paramMap.get("value").toString(), dataMap);
            			}
            		}else if("AEL".equals(paramMap.get("type"))) {
            			if(!StringUtils.isEmpty(paramMap.get("value"))){
            				FunctionCalculator.computeAviator(paramMap.get("value").toString(), dataMap);
            			}
            		}else if("MEL".equals(paramMap.get("type"))) {
            			if(!StringUtils.isEmpty(paramMap.get("value"))){
            				FunctionCalculator.computeMVEL(paramMap.get("value").toString(), dataMap);
            			}
            		}else {
            			dataMap.put(beSectionParameter.getParamId() + "_DISPLAY_TYPE", beSectionParameter.getDisplayType());
            			dataMap.put(beSectionParameter.getParamId(), beSectionParameter.getParamValue());
            		}
            	}
            }
        }
        return Response.ok(dataMap);
    }

    @ApiOperation(value = "查询规费", notes = "根据项目id查询规费")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "父节点", required = true, dataType = "String", paramType = "query")})
    @GetMapping("/getGFSJTree")
    public Response<Map<String, List<Map<String, Object>>>> getGFSJTree(@RequestParam("sectionId") String sectionId,
                                                                        @RequestParam("parentId") String parentId) {
        Map<String, List<Map<String, Object>>> returnMap = Maps.newHashMap();
        returnMap.put("tableData", beSectionParameterService.selectGFSJTree(sectionId, parentId));
        return Response.ok(returnMap);
    }

    @ApiOperation(value = "查询措施费率", notes = "根据项目id查询措施费率")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "父节点", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "工程性质", required = true, dataType = "String", paramType = "query")})
    @GetMapping("/getCSFLTree")
    public Response<Map<String, List<Map<String, Object>>>> selectCSFLTree(@RequestParam("sectionId") String sectionId,
                                                                           @RequestParam("parentId") String parentId,@RequestParam("type") String type) {
        Map<String, List<Map<String, Object>>> returnMap = Maps.newHashMap();
        returnMap.put("tableData", beSectionParameterService.selectCSFLTree(sectionId, parentId,type));
        return Response.ok(returnMap);
    }

    @ApiOperation(value = "查询技术评审项目", notes = "根据项目id查询技术评审项目")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "父节点", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "技术标评审类型 0:通过型通过制 1：打分型通过制（总分平均）2：打分型通过制（细项平均)  3：细项平均打分制  4:总分平均打分制", required = true, dataType = "String", paramType = "query")})
    @GetMapping("/getTecItemTree")
    public Response<Map<String, List<Map<String, Object>>>> selectTecItemTree(@RequestParam("sectionId") String sectionId,
                                                                              @RequestParam("parentId") String parentId, String type) {
        Map<String, List<Map<String, Object>>> returnMap = Maps.newHashMap();
        returnMap.put("tableData", beTechnologyItemService.selectTree(sectionId, parentId, type));
        return Response.ok(returnMap);
    }

    @ApiOperation(value = "查询资信审项目", notes = "根据项目id查询查询资信评审项目")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "父节点", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "技术标评审类型 0:通过型通过制 1：打分型通过制（总分平均）2：打分型通过制（细项平均)  3：细项平均打分制  4:总分平均打分制", required = true, dataType = "String", paramType = "query")})
    @GetMapping("/getQualItemTree")
    public Response<Map<String, List<Map<String, Object>>>> selectQualItemTree(@RequestParam("sectionId") String sectionId,
                                                                               @RequestParam("parentId") String parentId, String type) {
        Map<String, List<Map<String, Object>>> returnMap = Maps.newHashMap();
        returnMap.put("tableData", beQualificateItemService.selectTree(sectionId, parentId, type));
        return Response.ok(returnMap);
    }

    @ApiOperation(value = "查询清单单位工程", notes = "根据项目id查询清单单位工程")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "暂时默认为2", required = true, dataType = "String", paramType = "query")})
    @GetMapping("/getManagerNodeList")
    public Response<List<Map<String, Object>>> selectManagerNodeList(@RequestParam("sectionId") String sectionId, @RequestParam("type") String type) {
        return Response.ok(beManagerNodeService.selectList(sectionId, type));
    }

    @ApiOperation(value = "查询所有清单列表", notes = "根据项目id和单位工程id查询所有清单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "managerNodeId", value = "单位工程id", required = true, dataType = "String", paramType = "query")})
    @GetMapping("/getAllBudgeList")
    public Response<List<Map<String, Object>>> selectAllBudgetList(@RequestParam("sectionId") String sectionId, @RequestParam("managerNodeId") String managerNodeId) {
        return Response.ok(beBudgetItemService.selectAllList(sectionId, managerNodeId));
    }

    @ApiOperation(value = "查询已选择清单列表", notes = "根据项目id查询已选择清单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段id", required = true, dataType = "String", paramType = "query")})
    @GetMapping("/getCheckBudgeList")
    public Response<List<Map<String, Object>>> selectCheckList(@RequestParam("sectionId") String sectionId) {
        return Response.ok(beBudgetItemService.selectCheckList(sectionId));
    }

    @ApiOperation(value = "按参数代码集合查询所有参数列表", notes = "按参数代码集合查询所有参数列表", response = BeSectionParameter.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段ID", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "paramIds", value = "参数代码,格式（zbkzj,k1）", required = true,
                    dataType = "String", paramType = "query"),
    })
    @ApiResponses({
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_ONE, message = "参数不可以为空！"),
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_TWO, message = "获取数据错误，请联系管理员！"),
    })
    @GetMapping("/queryListByParamIds")
    public Response<List<BeSectionParameter>> queryListByParamIds(@RequestParam("sectionId") String sectionId, @RequestParam("paramIds") String paramIds) {
        if (StringUtils.isEmpty(sectionId) || StringUtils.isEmpty(paramIds)) {
            return Response.fail("参数不可以为空！", Constants.FIVE_HUNDRED_AND_ONE);
        }
        Response<String> msg;
        try {
            //参数已经获取过不需要再次获取(K1和K2不存在则重新获取参数)
            if (Constants.TRUE.equals(isCallInterface) && beSectionParameterService.queryListByParamIds(sectionId, new String[]{K1, K2, DOWN_RATE}).size() < Constants.ONE) {
                BeSectionInfo beSectionInfo = beSectionInfoService.getBeSectionInfoById(sectionId);
                //触发参数获取接口
                msg = bidParamService.getK1K2(beSectionInfo.getSectionCode());
                if(Constants.FIVE_HUNDRED == msg.getStatus()){
                    log.info("标段[" + beSectionInfo.getSectionName() + "]获取评标参数错误信息：" + msg.getError());
                }
                //同步参数到评标库的参数表
                List<BeSectionParameter> parameterList = new ArrayList<>();
                BeSectionParameter beSectionParameter;
                for (Map<String, Object> dataMap : beSectionParameterService.queryTdAuditparaBytype(beSectionInfo.getTdProjectid(), Constants.TWO)) {
                    //开标抽取的值（原始数据）
                    beSectionParameter = new BeSectionParameter();
                    beSectionParameter.setSectionId(sectionId);
                    beSectionParameter.setParamType("1");
                    beSectionParameter.setParamId(OConvertUtils.getString(dataMap.get("paraName")));
                    beSectionParameter.setParamValue(OConvertUtils.getString(dataMap.get("paraValue")));
                    beSectionParameter.setCreateTime(DateUtil.now());
                    beSectionParameter.setUpdateTime(DateUtil.now());
                    //代理页面展示的值，代理可以修改
                    parameterList.add(beSectionParameter);
                    beSectionParameter = new BeSectionParameter();
                    beSectionParameter.setSectionId(sectionId);
                    beSectionParameter.setParamType("3");
                    if (K1.equals(OConvertUtils.getString(dataMap.get("paraName")))) {
                        beSectionParameter.setParamId("qzxs");
                    } else if (K2.equals(OConvertUtils.getString(dataMap.get("paraName")))) {
                        beSectionParameter.setParamId("fdxs");
                    } else if (DOWN_RATE.equals(OConvertUtils.getString(dataMap.get("paraName")))) {
                        beSectionParameter.setParamId("cqxfbl");
                    }
                    beSectionParameter.setParamValue(OConvertUtils.getString(dataMap.get("paraValue")));
                    beSectionParameter.setCreateTime(DateUtil.now());
                    beSectionParameter.setUpdateTime(DateUtil.now());
                    parameterList.add(beSectionParameter);
                }
                if (!beSectionParameterService.saveSectionParameter(parameterList)) {
                    throw new Exception("评标参数同步失败！");
                }
            }
            return Response.ok(beSectionParameterService.queryListByParamIds(sectionId, paramIds.split(",")));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("获取数据错误，请联系管理员！", Constants.FIVE_HUNDRED_AND_TWO);
        }
    }


    @ApiOperation(value = "批量保存评标参数", notes = "批量保存评标参数")
    @ApiResponses({
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_ONE, message = "参数不可以为空！"),
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_TWO, message = "保存失败！"),
            @ApiResponse(code = Constants.FIVE_HUNDRED_AND_THREE, message = "保存异常，请联系管理员！"),
    })
    @PostMapping("/saveSectionParameter")
    public Response saveSectionParameter(@ApiParam(value = "评标参数") @RequestBody() List<BeSectionParameter> dataList) {
        if (dataList == null || dataList.isEmpty()) {
            return Response.fail("参数不可以为空！", Constants.FIVE_HUNDRED_AND_ONE);
        }
        try {
            if (beSectionParameterService.saveSectionParameter(dataList)) {
                return Response.ok("保存成功！");
            }
            return Response.fail("保存失败！", Constants.FIVE_HUNDRED_AND_TWO);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Response.fail("保存异常，请联系管理员！", Constants.FIVE_HUNDRED_AND_THREE);
        }
    }
}
